#define _BSD_SOURCE 0
#include <pcap.h>
#include <headers.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
#include <net/ethernet.h>
#include <netinet/ether.h>

//This code sniffs for a single tcp packet. I got this off the tcpdump pcap tutorial. 
//Change the filter_exp variable to change the filter. The full set can be looked up.
//Change the device in the dev variable. just choose a good network interface.
//This must be run with admin privileges. Be sure to include -lpcap in the gcc call. I installed libpcap-dev.
// 0 - data send
// 1 - ack sent
typedef struct sequence {
  int status;
  int startTime;
  int sequence;
} Sequence;
typedef struct connection {
  char * src;
  char * dst;
  int avgrtt;
  Sequence * waiting;
} Connection;

	 int main(int argc, char *argv[])
	 {
		pcap_t *handle;			/* Session handle */
		char *dev;			/* The device to sniff on */
		char errbuf[PCAP_ERRBUF_SIZE];	/* Error string */
		struct bpf_program fp;		/* The compiled filter */
		char filter_exp[] = "tcp";	/* The filter expression */
		bpf_u_int32 mask;		/* Our netmask */
		bpf_u_int32 net;		/* Our IP */
		struct pcap_pkthdr header;	/* The header that pcap gives us */
		const u_char *packet;		/* The actual packet */
		int i;
		
		/* Define the device */
		dev = "wlan0";
		/* Find the properties for the device */
		if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
			fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
			net = 0;
			mask = 0;
		}
		/* Open the session in promiscuous mode */
		handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
		if (handle == NULL) {
			fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
			return(2);
		}
		/* Compile and apply the filter */
		if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
			fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
			return(2);
		}
		if (pcap_setfilter(handle, &fp) == -1) {
			fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
			return(2);
		}
		/* Grab a packet */

		while(1) {
		  packet = pcap_next(handle, &header);
		  if (header.len < 32000) {
		    //get sequence number
		    //if ack
		    //    if receiving
		    //         find correct start status with matching sequence number
		    ////  if sending
		    //         start ack send state
		    //else if data
		    //    if receving
		    //         find correct start ack with sequnce number -1
		    //    if sending
		    //         start data send state
		  }
		  
		  
		}
		/* Print its length */
		/* And close the session */
		pcap_close(handle);
		free(connections);
		return(0);
	 }
